﻿using Light.Framework;
using Light.Utility;
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Test.Models;
using System.Transactions;
using Light.Aop;
using System.Threading;

namespace Test
{


    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            //SearchArgs args = new SearchArgs();
            //args.Add(SearchLogic.And, "FName", SearchOperator.InSql, "select fname from DemoUser where  fname like 'Thread_2%'");
            //DataTableMediator.GetAll("DemoUser", args, null, null);

            //SearchArgs args = new SearchArgs();
            //args.Add(SearchLogic.And, "Name", SearchOperator.InSql, "select fname from DemoUser where  fname like 'Thread_2%'");
            //List<DemoUser> list = EntityMediator<DemoUser>.GetAll(args, null, null);



            //Test t = new Test();

            //t.Name = "1111";

            //t.DoSomething(2);


            //IAdminUserComponent comp = Light.IoC.Factory.Current.Create<IAdminUserComponent>("AdminUser");

            //DataTable dt = DataTableMediator.GetAll("DemoUser", null, null, null, 10);

            //OperateColumn columns = new OperateColumn();
            //columns.Retain("ID");
            //columns.Rename("FName", "Name");
            //columns.Remove("Creater_ID");

            //DataTable dtNew = DataTableHelper.ToDataTable(dt, columns);

            //SearchArgs args = new SearchArgs();
            //args.Add(SearchLogic.And, "Creater.ID", SearchOperator.In, "java_test_0000387189824", null);
            //args.Add(SearchLogic.And, "IsSuper", SearchOperator.In, false, null);
            //string sql = args.ToString<DemoUser>();
            //EntityMediator<DemoUser>.GetAll(args, null, null);
            //Response.Write(sql);



            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            //sw.Start();

            //using (TransactionScope ts = new TransactionScope())
            //{

            for (int i = 0; i < 500; i++)
            {
                Thread thread = new Thread(DoTask);
                thread.Name = "Thread_" + i;
                thread.Start();
            }


            //ts.Complete();
            //}
            //sw.Stop();

            //int count = EntityMediator<DemoUser>.Count(null);

            //Response.Write("耗时：" + sw.ElapsedMilliseconds + " 共，" + count);
            //string reseved = "<Protocol><PNo>YYYY10DD1410SS59413786130596</PNo><TS>YYYY10DD1410SS</TS><MchNo>P0020227</MchNo><Seq>1410SS633YYYY10DD</Seq><URL>http://newdata.maicaim.com/Restaurant/CMB/PayOrderResult.aspx</URL><Para>TSuppc2322144e53a4a49bea1ec18ab23bcde</Para><MUID></MUID><Mobile>13786130596</Mobile><LBS>102.713338|25.049321</LBS><RskLvl></RskLvl></Protocol>";

            //string temp = Light.Utility.CMB.OneNetPayHelper.GetMerchantCode("", "20161012", "0755", "1234", "215464564", "1.00", "", "dddddd", "", "", "127.0.0.1", "44444", reseved);


            //Response.Write(temp);
            //Response.End();

            //string str = CHPinYinConver.PinYinConver.ConvertToPinYin();

            //string str = "测试用户123ABCa(]}]}}【|";
            //string result = string.Empty;

            //Regex regex = new Regex("[\u4e00-\u9fa5]");


            //foreach (char c in str)
            //{
            //    Match m = regex.Match(c.ToString());
            //    if (m.Success)
            //    {
            //        result += CHPinYinConver.PinYinConver.ConvertToPinYin(c.ToString());
            //    }
            //    else
            //    {
            //        result += c.ToString();
            //    }
            //}

            //lblResult.Text = result;
        }

        private static void DoTask()
        {

            List<DemoUser> objs = new List<DemoUser>();
            for (int j = 0; j < 1000; j++)
            {
                DemoUser obj = new DemoUser();
                obj.Name = Thread.CurrentThread.Name + "_obj_" + j;
                obj.Number = Guid.NewGuid().ToString("N");
                obj.TimeCreated = DateTime.Now;
                objs.Add(obj);
            }
            EntityMediator<DemoUser>.Create(objs);

        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            DemoUser user = new DemoUser();
            //user.ID = Guid.NewGuid().ToString("N");
            user.Name = "测试用户_" + DateTime.Now.ToString("mmss");
            user.TimeCreated = DateTime.Now;
            //user.Creater = EntityMediator<DemoUser>.Get("01745cf4-901f-4375-80af-60c57364e19c", new ResultColumn());

            OperateResult result = EntityMediator<DemoUser>.Create(user);
            lblResult.Text = result.Message;

            BindDatas();
        }

        protected void btnTransaction_Click(object sender, EventArgs e)
        {
            try
            {
                //启用事务
                using (TransactionScope ts = new TransactionScope())
                {
                    DemoUser user = new DemoUser();

                    user.Name = "测试用户_" + DateTime.Now.ToString("mmss");
                    user.TimeCreated = DateTime.Now;

                    OperateResult result = EntityMediator<DemoUser>.Create(user);

                    //制造异常：插入相同主键
                    result = EntityMediator<DemoUser>.Create(user);
                    lblResult.Text = result.Message;

                    //提交事务，如果上面代码发生异常，将自动回滚
                    ts.Complete();
                }
            }
            catch (Exception ex)
            {

                lblResult.Text = ex.Message + " ，回滚成功！";
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindDatas();
        }

        private void BindDatas()
        {
            SearchArgs searchArgs = new SearchArgs();
            if (!String.IsNullOrEmpty(txtKeywords.Text.Trim()))
            {
                searchArgs["Name"] = txtKeywords.Text.Trim();
            }

            PageArgs pageArgs = new PageArgs();
            pageArgs.PageSize = 20;

            ResultOrder resultOrder = new ResultOrder();
            resultOrder["TimeCreated"] = false;

            List<DemoUser> models = EntityMediator<DemoUser>.Search(searchArgs, pageArgs, resultOrder, null);
            this.GridView1.DataSource = models;
            this.GridView1.DataBind();

            lblPageTotal.Text = pageArgs.TotalPages.ToString();
            lblTotalResults.Text = pageArgs.TotalResults.ToString();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = this.GridView1.DataKeys[0].Value.ToString();
            OperateResult result = EntityMediator<DemoUser>.Delete(id);
            lblResult.Text = result.Message;

            BindDatas();
        }
    }

    [CacheClass]
    public class Test : ContextBoundObject
    {
        public string Name { get; set; }

        [CacheMethod]
        public int DoSomething(int x)
        {
            return x + 100 / x;
        }
    }
}